<template>
  <div class="app-container">
    <h1>任务创建</h1>
    <el-card class="box-card">
      <el-form :model="taskForm" label-width="120px" ref="taskForm" class="form-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务名称">
              <el-input v-model="taskForm.name" placeholder="请输入任务名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期">
              <el-date-picker v-model="taskForm.startDate" type="date" placeholder="选择开始日期"
                style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结束日期">
              <el-date-picker v-model="taskForm.endDate" type="date" placeholder="选择结束日期"
                style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述">
              <el-input v-model="taskForm.description" type="textarea" :rows="3" placeholder="请输入任务描述"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="关联果园">
          <el-select v-model="taskForm.orchardIds" multiple placeholder="请选择果园" style="width: 100%;">
            <el-option v-for="orchard in orchards" :key="orchard.id" :label="orchard.name"
              :value="orchard.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所需物资">
          <el-button @click="showMaterialDialog = true" type="primary" icon="el-icon-plus">分配物资</el-button>
          <el-table :data="taskForm.materials" border style="width: 100%; margin-top: 10px;">
            <el-table-column prop="material.name" label="物资名称"></el-table-column>
            <el-table-column prop="requiredQuantity" label="所需数量">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.requiredQuantity" :min="1" size="mini"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="removeMaterial(scope.$index)" type="text" size="mini">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="执行人员">
          <el-select v-model="taskForm.executorIds" multiple placeholder="请选择执行人员" style="width: 100%;">
            <el-option v-for="user in users" :key="user.userId" :label="user.username" :value="user.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" style="margin-right: 10px;">创建任务</el-button>
          <el-button @click="resetForm('taskForm')">取消</el-button>
        </el-form-item>
      </el-form>

      <!-- 物资选择对话框 -->
      <el-dialog title="选择物资" :visible.sync="showMaterialDialog" width="40%">
        <el-select v-model="selectedMaterialId" filterable placeholder="请选择物资" style="width: 100%;">
          <el-option v-for="material in materials" :key="material.id" :label="material.name"
            :value="material.id"></el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showMaterialDialog = false">取 消</el-button>
          <el-button type="primary" @click="addSelectedMaterial">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>



<script>
import { mapState, mapActions } from 'vuex';

export default {
  data() {
    return {
      taskForm: {
        name: '',
        startDate: null,
        endDate: null,
        description: '',
        orchardIds: [], // 关联果园ID数组
        materials: [], // 所需物资及其数量
        executorIds: [] // 执行人员ID数组
      },
      showMaterialDialog: false,
      selectedMaterialId: null
    };
  },
  computed: {
    ...mapState('user', ['users']),
    ...mapState('orchardinfo', ['orchards']),
    ...mapState('supplies', {
      materials: state => state.supplies,
    }),
    ...mapState('task', ['tasks']) // 如果你需要显示任务列表
  },
  methods: {
    ...mapActions('user', ['loadUsers']),
    ...mapActions('orchardinfo', ['fetchOrchards']),
    ...mapActions('supplies', ['fetchSupplies']),
    ...mapActions('task', ['addTask']), // 映射 addTask 动作

    submitForm() {
      console.log(this.taskForm);
      this.addTask(this.taskForm).then(() => {
        this.$message.success('任务创建成功！');
        this.resetForm('taskForm');
        // 添加跳转逻辑
        this.$nextTick(() => {
          this.$router.push({ name: 'TrackProgress' });
        });
      }).catch(error => {
        this.$message.error('任务创建失败，请重试。');
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addSelectedMaterial() {
      const material = this.materials.find(m => m.id === this.selectedMaterialId);
      if (material && !this.taskForm.materials.some(item => item.material.id === material.id)) {
        this.taskForm.materials.push({ material, requiredQuantity: 1 });
      } else if (!material) {
        this.$message.error('请选择有效的物资');
      } else {
        this.$message.warning('该物资已经添加');
      }
      this.showMaterialDialog = false;
    },
    removeMaterial(index) {
      this.taskForm.materials.splice(index, 1);
    }
  },
  created() {
    this.loadUsers();
    this.fetchOrchards();
    this.fetchSupplies();
    // 如果你需要加载任务列表，可以在创建时调用 fetchTasks
    // this.fetchTasks();
  }
};
</script>


<style scoped>
.app-container {
  padding: 10px;
  text-align: left;
  /* 整体内容靠左 */
}

h1 {
  text-align: center;
  color: #303133;
  margin-bottom: 20px;
}

.box-card {
  margin-top: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 确保表单容器靠左，移除所有可能导致居中的样式 */
.form-container {
  max-width: none;
  /* 移除最大宽度限制 */
  width: auto;
  /* 宽度自适应内容 */
  margin: 0;
  /* 移除外边距 */
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--text {
  color: #409eff;
}

.el-button--text:hover {
  color: #409eff;
}

.el-table__body-wrapper {
  overflow-x: hidden;
}

.el-button--mini {
  font-size: 12px;
  padding: 7px 15px;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__footer {
  text-align: right;
  padding: 10px 20px 15px;
  border-top: 1px solid #ebeef5;
}

.el-select {
  width: 100%;
}</style>
